/**
 * 簿记交收
 * @author zhangxinyue(2021-02-09)
 */
import { message } from 'antd';
import moment from 'moment';

import api from '../../api';
import typeConfig from '../../comps/business/tradingDirect/config';
import config from '../../comps/business/tradingMarket/config';
import findKeyword from '../../routes/PortfolioMnt/BookkeepingMnt/findKeyword';
import typeOfTradeX from '../../routes/PortfolioMnt/BookkeepingMnt/typeOfTradeX.js';
import delegationTypeData from '../../utils/enumeratedValues/delegationTypeData';
import { fixedNum } from '../../utils/utils';

export default {
  namespace: 'bookkeepingSettleM',
  state: {},
  effects: {
    // 获取簿记列表
    *getList({ payload, callback }, { call }) {
      const res = yield call(api.bookkeepingSettle.getList, payload);
      if (res && res.success) {
        res.data &&
          res.data.map((item) => {
            if (item.type == '17') {
              // 中签状态 拿到外层 方便使用tableC操作按钮
              item.bondOffStatus = item.trade17.status;
            }
          });
        callback({
          pageInfo: {
            total: res.total,
            currentPage: res.current,
            pageSize: res.pageSize,
          },
          dataSource: res.data,
          columns: [
            {
              title: '日期',
              dataIndex: 'createdTs',
              key: 'createdTs',
              workStation: true,
              width: 120,
              render: (val) => <span>{moment(val).format('YYYY-MM-DD')}</span>,
            },
            {
              title: '产品名称',
              dataIndex: 'productName',
              key: 'productName',
              width: 150,
              workStation: true,
            },
            {
              title: '组合名称',
              dataIndex: 'portfolioInfoName',
              key: 'portfolioInfoName',
              width: 150,
            },
            {
              title: '证券代码',
              dataIndex: 'tradingCode',
              key: 'tradingCode',
              workStation: true,
              width: 120,
            },
            {
              title: '证券名称',
              dataIndex: 'tradingName',
              key: 'tradingName',
              width: 150,
            },
            {
              title: '交易市场',
              dataIndex: 'securityExchange',
              key: 'securityExchange',
              width: 120,
              render: (val, record) => {
                const trade = typeOfTradeX(record);
                if (trade) {
                  if (record.type == 8) {
                    return '银行间';
                  }
                  const findvalue = config.filter((item) => item.value == trade.exchangeCode);
                  if (findvalue && findvalue.length > 0) {
                    return findvalue[0].title;
                  }
                  return '--';
                }
              },
            },
            {
              title: '资产类型',
              dataIndex: 'type',
              key: 'type',
              width: 140,
              render: (val, record) => {
                const findType = typeConfig.filter((item) => item.value == (record.type == 33 ? 32 : record.type));
                if (findType && findType.length > 0) {
                  return findType[0].title;
                }
                return '--';
              },
            },
            {
              title: '投资类型',
              dataIndex: 'investmentType',
              key: 'investmentType',
              width: 90,
            },
            {
              title: '交易方向',
              dataIndex: 'orderSide',
              key: 'orderSide',
              workStation: true,
              width: 90,
              render: (val, record) => {
                // 根据业务类型，翻译交易方向
                const trade = typeOfTradeX(record);
                if (trade) {
                  const findtypes = typeConfig.filter((item) => item.value == (record.type == 33 ? 32 : record.type));
                  if (findtypes && findtypes.length > 0) {
                    const findorderSide = findtypes[0].tradingDirect.filter((item) => item.value == findKeyword(trade, record, 'orderSide'));
                    if (findorderSide && findorderSide.length > 0) {
                      if (record.type == '3') {
                        // 当业务类型为 3-协商成交，那么交易方向特殊处理成“方向-委托类型”
                        const delegationType = delegationTypeData.filter((item) => item.value == trade.delegationType);
                        return `${findorderSide[0].title}-${delegationType[0]?.title}`;
                      }
                      return findorderSide[0].title;
                    }
                    return '--';
                  }
                  return '--';
                }
              },
            },
            {
              title: '交易数量',
              dataIndex: 'tAmount',
              key: 'tAmount',
              type: 'number',
              workStation: true,
              width: 110,
              render: (val, record) => {
                const trade = typeOfTradeX(record);
                if (record.type == '13') {
                  if (trade.pledgeVo[0]) {
                    return +trade.pledgeVo[0].transactionAmount / 100;
                  }
                  return '--';
                }
                return findKeyword(trade, record, 'tAmount');
              },
            },
            {
              title: '价格（净价）',
              dataIndex: 'price',
              key: 'price',
              type: 'money',
              width: 110,
              render: (val, record) => {
                const trade = typeOfTradeX(record);
                if (record.type == '5') {
                  // if(record.instructionStatus=='7'||record.instructionStatus=='8'){
                  //   if(trade.applyNum==null){
                  //     return '--'
                  //   }
                  //   return +trade.applyAmount/trade.applyNum
                  // }else{
                  //   return '--'
                  // }
                  if (trade.applyNum == null || trade.applyNum == undefined||trade.applyAmount==null) {
                    return '--';
                  }
                  return Number(+trade.applyAmount / trade.applyNum).toFixed(4);
                }
                return findKeyword(trade, record, 'price', 'moneys');
              },
            },
            {
              title: '价格（全价）',
              dataIndex: 'amount',
              key: 'amount',
              type: 'money',
              workStation: true,
              className: 'column-right',
              width: 110,
              render: (val, record) => {
                const trade = typeOfTradeX(record);
                if (findKeyword(trade, record, 'amount', 'moneys')) {
                  return findKeyword(trade, record, 'amount', 'moneys');
                }
                if(findKeyword(trade, record, 'amount', 'moneys')=='') return '';//展示为空白
                return fixedNum(val);
              },
            },
            {
              title: '利率（%）',
              dataIndex: 'repoRate',
              key: 'repoRate',
              type: 'rate',
              className: 'column-right',
              width: 90,
              render: (val, record) => {
                const trade = typeOfTradeX(record);
                if (trade) {
                  if (record.type == '7') {
                    const num = findKeyword(trade, record, 'orderSide');
                    if (num == 3 || num == 4) {
                      return;
                    }
                  }
                  if (record.type === '8') {
                    if (record.trade8.orderSize == 'F') {
                      return findKeyword(trade, record, 'repoRateF', 'rate');
                    } else if (record.trade8.orderSize == 'i') {
                      return findKeyword(trade, record, 'repoRateI', 'rate');
                    }
                    return '--';
                  }
                }
                return findKeyword(trade, record, 'repoRate', 'rate');
              },
            },
            {
              title: '交易金额',
              dataIndex: 'settlementAmount',
              key: 'settlementAmount',
              type: 'money',
              className: 'column-right',
              workStation: true,
              width: 120,
              render: (val, record) => {
                const trade = typeOfTradeX(record);
                if (trade) {
                  if (record.type === '8') {
                    if (record.trade8.orderSize == 'F') {
                      return findKeyword(trade, record, 'settlementAmountF', 'rate');
                    } else if (record.trade8.orderSize == 'i' || record.trade8.orderSize == 'calc') {
                      return findKeyword(trade, record, 'settlementAmountI', 'rate');
                    }
                    return '--';
                  }
                }

                return findKeyword(trade, record, 'settlementAmount', 'money');
              },
            },
            {
              title: '清算速度',
              dataIndex: 'settlementSpeed',
              key: 'settlementSpeed',
              width: 90,
              render: (val, record) => {
                const trade = typeOfTradeX(record);
                if (trade) {
                  const newSettlementSpeed = findKeyword(trade, record, 'settlementSpeed');
                  if (newSettlementSpeed == '1') {
                    return 'T+0';
                  }
                  if (newSettlementSpeed == '2') {
                    return 'T+1';
                  }
                  if (newSettlementSpeed == '0') {
                    return 'T+0';
                  }
                }
              },
            },
            {
              title: '交易对手',
              dataIndex: 'externalName',
              key: 'externalName',
              width: 100,
              render: (val, record) => {
                const trade = typeOfTradeX(record);
                if (trade) {
                  if (['1', '2', '3', '4', '16', '25', '32', '33'].includes(record.type)) {
                    if (record.externalName === null || record.externalName === undefined) {
                      return '--';
                    }
                    return record.externalName;
                  }
                  return findKeyword(trade, record, 'externalName');
                }
              },
            },
            // {
            //   title: '交收日期',
            //   dataIndex: 'settlementDate',
            //   key: 'settlementDate',
            //   render: (val, record) => {
            //     let trade = typeOfTradeX(record)
            //     if (trade) {
            //       let settlementDates = findKeyword(trade, record, 'settlementDate')
            //       if(settlementDates!='--'&&settlementDates!=''){
            //         return moment(settlementDates).format('YYYY-MM-DD')
            //       }else{
            //         return settlementDates
            //       }
            //     }
            //   },
            // },
            {
              title: '状态',
              dataIndex: 'instructionStatus',
              key: 'instructionStatus',
              workStation: true,
              width: 90,
              render: (val) => {
                switch (val) {
                  case '6':
                    return '未交收';
                  case '4':
                    return '已交收';
                  case '7':
                    return '已交收';
                  case '8':
                    return '到期交收';
                  case '11':
                    return '到期未交收';
                  default:
                    return null;
                }
                // let trade = typeOfTradeX(record)
                // if (trade) {
                //   let settlementDates = findKeyword(trade, record, 'settlementDate')
                //   if(settlementDates!='--'&&settlementDates!=''){
                //     switch (val) {
                //       case '6': return `未交收(${moment(settlementDates).format('YYYY-MM-DD')})`;
                //       case '4': return `已交收(${moment(settlementDates).format('YYYY-MM-DD')})`;
                //       case '7': return `已交收(${moment(settlementDates).format('YYYY-MM-DD')})`;
                //       case '8': return `到期交收(${moment(settlementDates).format('YYYY-MM-DD')})`;
                //       case '11': return `到期未交收(${moment(settlementDates).format('YYYY-MM-DD')})`;
                //     }
                //   }else{
                //     switch (val) {
                //       case '6': return "未交收";
                //       case '4': return "已交收";
                //       case '7': return "已交收";
                //       case '8': return "到期交收";
                //       case '11': return "到期未交收";
                //     }
                //   }
                // }
              },
            },
            {
              title: '首期交收方式',
              dataIndex: 'jsType',
              key: 'jsType',
              width: 170,
              render: (val, record) => {
                switch (val) {
                  case '0':
                    return record.settleDateStr ? `自动交收(${record.settleDateStr})` : '自动交收';
                  case '1':
                    return record.settleDateStr ? `手动交收(${record.settleDateStr})` : '手动交收';
                  default:
                    return '--';
                }
              },
            },
            {
              title: '到期交收方式',
              dataIndex: 'dqjsType',
              key: 'dqjsType',
              width: 120,
              render: (val, record) => {
                // 债券指令到期交收方式展示--
                const list = ['0', '1', '2', '3', '25'];
                if (list.includes(record.type)) {
                  return '--';
                }
                switch (val) {
                  case '0':
                    return record.dqsettleDateStr ? `自动交收(${record.dqsettleDateStr})` : '自动交收';
                  case '1':
                    return record.dqsettleDateStr ? `手动交收(${record.dqsettleDateStr})` : '手动交收';
                  default:
                    return '--';
                }
              },
            },
          ],
        });
      } else {
        callback();
        message.error(res?.message);
      }
    },
    // 交收
    *getTradeInstruction({ payload, callback }, { call }) {
      const response = yield call(api.bookkeepingSettle.getTradeInstruction, payload);
      if (response && response.success) {
        callback('success');
        message.success('交收成功');
      } else {
        callback('fail');
        message.error(response.message || '交收失败!');
      }
    },
    // 回溯
    *getTradeInstructionHS({ payload, callback }, { call }) {
      const response = yield call(api.bookkeepingSettle.getTradeInstructionHS, payload);
      if (response && response.success) {
        callback('success');
        message.success('回溯成功');
      } else {
        callback('fail');
        message.error(response.message || '回溯失败!');
      }
    },
    // 成交信息
    *clinchInfromation({ payload, callback }, { call }) {
      const response = yield call(api.bookkeepingSettle.clinchInfromation, payload);
      if (response && response.code == 0) {
        callback(response.data);
      } else {
        callback();
        message.error(response.message || '成交信息查询失败!');
      }
    },
  },
  reducers: {
    updateData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {},
};
